package com.yhgarden.bbs.service.impl.common;

import com.yhgarden.bbs.entity.common.Adjunct;
import com.yhgarden.bbs.mapper.common.AdjunctMapper;
import com.yhgarden.bbs.model.enums.StatusCode;
import com.yhgarden.bbs.model.response.BaseResponse;
import com.yhgarden.bbs.service.api.common.AdjunctService;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.util.ThumbnailatorUtils;
import org.apache.catalina.connector.ClientAbortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
public class AdjunctServiceImpl implements AdjunctService {
    private static Logger logger = LoggerFactory.getLogger(AdjunctServiceImpl.class);

    @Value("${file.uploadPath}")
    private String uploadPath;

    @Autowired
    private AdjunctMapper adjunctMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse fileUpload(MultipartFile[] importFiles, HttpServletRequest request) throws IOException {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        File dir = new File(uploadPath);
        //如果文件夹不存在则新建文件夹
        if(!dir.exists()){
            dir.mkdir();
        }
//        String serverpath = "/upfile";
        //指定地址存放附件，不要放在tomcat或者工程目录下
//        String realpath = uploadPath + serverpath;
        String realpath = uploadPath;
        List<Adjunct> result = new ArrayList<>();
        if(importFiles!=null&&importFiles.length>0){
            Date day = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String date = df.format(day);
            realpath += "/" + date;
            //循环获取文件数组中的文件
            for(int i = 0;i<importFiles.length;i++){
                MultipartFile importFile = importFiles[i];
                String fileFileName = importFile.getOriginalFilename();
                String prefix = fileFileName.substring(fileFileName.lastIndexOf(".")+1);
                fileFileName = fileFileName.replace("."+prefix,"");
                String fileContentType = importFile.getContentType();
                //生成新的文件名
                String newFileName = UUID.randomUUID().toString().replace("-", "");
                newFileName = newFileName+"."+prefix;
                if (importFile != null) {
                    double size = importFile.getSize() == 0 ? 0 : importFile.getSize() / 1024;
                    File savefile = new File(new File(realpath), newFileName);
                    if (!savefile.getParentFile().exists()) {
                        savefile.getParentFile().mkdirs();
                    }
                    importFile.transferTo(savefile);

                    try {
                        Adjunct adjunct = new Adjunct();
                        //生成UUID主键
                        String uuid = UUID.randomUUID().toString();
                        adjunct.setId(uuid);
                        adjunct.setPath(realpath + "/" + newFileName);
                        adjunct.setContentType(fileContentType);
                        adjunct.setTitle(fileFileName);
                        adjunct.setSize(size);
                        adjunct.setPrefix(prefix);
                        adjunctMapper.create(adjunct);
                        result.add(adjunct);
                    }catch (Exception e){
                        e.printStackTrace();
                        //如果发生异常，删除已经保存的文件
                        savefile.delete();
                    }
                } else {
                    response = new BaseResponse(StatusCode.FILE_NOT_FOUND);
                    return response;
                }
            }
        } else {
            response = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return response;
        }
        response.setData(result);
        return response;
    }

    @Override
    public BaseResponse getImageByUrl(String imageurl, String name) throws IOException {
        BaseResponse response = new BaseResponse(StatusCode.SUCCESS);
        File dir = new File(uploadPath);
        //如果文件夹不存在则新建文件夹
        if(!dir.exists()){
            dir.mkdir();
        }
        String serverpath = "/upfile";
        //指定地址存放附件，不要放在tomcat或者工程目录下
        String realpath = uploadPath + serverpath;
        Date day = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(day);
        realpath += "/" + date;
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        try {
            // 构造URL
            URL url = new URL(imageurl);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            is.available();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len = 0;
            File file = new File(realpath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 输出的文件流
            OutputStream os = new FileOutputStream(realpath + "/" + newFileName+".jpg");
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            file = new File(realpath + "/" + newFileName+".jpg");
            os.close();
            is.close();
            try {
                Adjunct adjunct = new Adjunct();
                String uuid = UUID.randomUUID().toString();
                adjunct.setId(uuid);
                adjunct.setSize(Double.valueOf(is.available()));
                adjunct.setContentType("image/jpeg");
                adjunct.setTitle(name);
                adjunct.setPrefix("jpg");
                adjunct.setPath(realpath + "/" + newFileName+".jpg");
                adjunctMapper.create(adjunct);

                response.setData(adjunct);
            }catch (Exception e){
                e.printStackTrace();
                //如果发生异常，删除已经保存的文件
                file.delete();
            }
        } catch (Exception e) {
            response = new BaseResponse(StatusCode.GET_IMAGE_FAIL);
            return response;
        }
        return response;
    }

    @Override
    public BaseResponse fileDownload(HttpServletResponse response, String adjunctId, String widthHeight) throws IOException {
        BaseResponse res = new BaseResponse(StatusCode.SUCCESS);
        //根据id查找附件对象
        Adjunct adjunct = adjunctMapper.getById(adjunctId);
        if(adjunct == null){
            res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return res;
        }
        String path = adjunct.getPath();
        String realFileName = adjunct.getTitle()+"."+adjunct.getPrefix();
        String contentType = adjunct.getContentType();
        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType(contentType);
//        response.setContentType("multipart/form-data");
        // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(realFileName.getBytes("utf-8"), "ISO8859-1"));
        ServletOutputStream out;
        // 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
        File file = new File(path);
        if(!file.exists()){
            res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return res;
        }
        String prefix = adjunct.getPrefix();
        //如果是图片，且宽高不为空
        if(ThumbnailatorUtils.isSupportedOutputFormat(prefix) && widthHeight != null ){
            String newPath = null;
            //判断旧版文件名
            if(path.contains("."+prefix)){
                String pathPre = path.substring(0,path.indexOf("."+prefix));
                newPath = pathPre + "_" + widthHeight + "."+prefix;
            }else {
                newPath = path + "_" + widthHeight + "."+prefix;
            }
            File newFile = new File(newPath);
            //判断一下该尺寸的缩略图是否存在
            if(!newFile.exists()){
                BufferedImage sourceImg = ImageIO.read(file);
                //获取源文件宽高
                int width = sourceImg.getWidth();
                int height = sourceImg.getHeight();

                //切割参数
                String[] widthHeightArr = widthHeight.split("x");
                int newWidth = Integer.parseInt(widthHeightArr[0]);
                int newHeight = Integer.parseInt(widthHeightArr[1]);
                //只有当文件尺寸小于原图时才缩放
                if(width > newWidth && height > newHeight){
                    double scaleWidth = (double)newWidth/(double)width;
                    double scaleHeight = (double)newHeight/(double)height;
                    //图片压缩
                    Thumbnails.of(file).scale(scaleWidth,scaleHeight).outputQuality(1f).outputFormat(prefix).toFile(newFile);
                    file = newFile;
                }
            }else{
                file = newFile;
            }
        }
//        WebFileUtils.downloadFile(file,response);
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        }catch (FileNotFoundException e){
            res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return res;
        }
        // 3.通过response获取ServletOutputStream对象(out)
        out = response.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len=inputStream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, len);
        }
        inputStream.close();
        out.close();
        out.flush();
        return res;
    }

    @Override
    public BaseResponse fileRangeDownload(HttpServletRequest request, HttpServletResponse response, String adjunctId) {
        BaseResponse res = new BaseResponse(StatusCode.SUCCESS);
        Adjunct adjunct = adjunctMapper.getById(adjunctId);
        if(adjunct == null){
            res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return res;
        }
        String path = adjunct.getPath();
        String realFileName = adjunct.getTitle()+"."+adjunct.getPrefix();
        File downloadFile = new File(path);

        // 文件不存在
        if (!downloadFile.exists()) {
            res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
            return res;
        }

        long fileLength = downloadFile.length();// 记录文件大小
        long pastLength = 0;// 记录已下载文件大小
        int rangeSwitch = 0;// 0：从头开始的全文下载；1：从某字节开始的下载（bytes=27000-）；2：从某字节开始到某字节结束的下载（bytes=27000-39000）
        long toLength = 0;// 记录客户端需要下载的字节段的最后一个字节偏移量（比如bytes=27000-39000，则这个值是为39000）
        long contentLength = 0;// 客户端请求的字节总量
        String rangeBytes = "";// 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容
        RandomAccessFile raf = null;// 负责读取数据
        OutputStream os = null;// 写出数据
        OutputStream out = null;// 缓冲
        int bsize = 1024;// 缓冲区大小
        byte b[] = new byte[bsize];// 暂存容器

        if (request.getParameter("showheader") != null) {
            Enumeration paramNames = request.getHeaderNames();

            while (paramNames.hasMoreElements()) {
                String name = paramNames.nextElement().toString();
                if (name != null && name.length() > 0) {
                    String value = request.getHeader(name);
                    System.out.println("************" + name + "：" + value);
                }
            }
        }
        String range = request.getHeader("Range");
        // if(range == null)
        // range = "bytes=0-";
        int responseStatus = 206;
        if (range != null && range.trim().length() > 0 && !"null".equals(range)) {// 客户端请求的下载的文件块的开始字节
            responseStatus = HttpServletResponse.SC_PARTIAL_CONTENT;
            System.out.println("request.getHeader(\"Range\")=" + range);
            rangeBytes = range.replaceAll("bytes=", "");
            if (rangeBytes.endsWith("-")) {// bytes=969998336-
                rangeSwitch = 1;
                rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                pastLength = Long.parseLong(rangeBytes.trim());
                contentLength = fileLength - pastLength;// 客户端请求的是
                // 969998336之后的字节（包括bytes下标索引为969998336的字节）
            } else {// bytes=1275856879-1275877358
                rangeSwitch = 2;
                String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length());
                // bytes=1275856879-1275877358，从第1275856879个字节开始下载
                pastLength = Long.parseLong(temp0.trim());
                toLength = Long.parseLong(temp2);// bytes=1275856879-1275877358，到第
                // 1275877358 个字节结束
                contentLength = toLength - pastLength + 1;// 客户端请求的是
                // 1275856879-1275877358
                // 之间的字节
            }
        } else {// 从开始进行下载
            contentLength = fileLength;// 客户端要求全文下载
        }

        /**
         * 如果设设置了Content-Length，则客户端会自动进行多线程下载。如果不希望支持多线程，则不要设置这个参数。 响应的格式是:
         * Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
         * ServletActionContext.getResponse().setHeader("Content-Length", new
         * Long(file.length() - p).toString());
         */
        // 来清除首部的空白行
        response.reset();
        // 告诉客户端允许断点续传多线程连接下载,响应的格式是:Accept-Ranges: bytes
        response.setHeader("Accept-Ranges", "bytes");
        // 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1

        // response.addHeader("Cache-Control", "max-age=1296000");
        // response.addHeader("Expires", "Fri, 12 Oct 2012 03:43:01 GMT");
        // response.addHeader("Last-Modified", "Tue, 31 Jul 2012 03:58:36 GMT");
        // response.addHeader("Connection", "keep-alive");
        // response.addHeader("ETag", downloadFile.getName() + "-" +
        // downloadFile.lastModified());
        // response.addHeader("Last-Modified", "Thu, 27 Sep 2012 05:24:44 GMT");
        if (rangeSwitch != 0) {
            response.setStatus(responseStatus);
            // 不是从最开始下载，断点下载响应号为206
            // 响应的格式是:
            // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
            System.out.println("----------------------------片段下载，服务器即将开始断点续传...");
            switch (rangeSwitch) {
                case 1: {// 针对 bytes=27000- 的请求
                    String contentRange = new StringBuffer("bytes ")
                            .append(new Long(pastLength).toString()).append("-")
                            .append(new Long(fileLength - 1).toString())
                            .append("/").append(new Long(fileLength).toString())
                            .toString();
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                case 2: {// 针对 bytes=27000-39000 的请求
                    String contentRange = range.replace("=", " ") + "/"
                            + new Long(fileLength).toString();
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                default: {
                    break;
                }
            }
        } else {
            String contentRange = new StringBuffer("bytes ").append("0-")
                    .append(fileLength - 1).append("/").append(fileLength)
                    .toString();
            response.setHeader("Content-Range", contentRange);
            // 是从开始下载
            System.out.println("----------------------------是从开始到最后完整下载！");
        }

        try {
            // /////////////////////////设置文件Content-Type///////////////////////////

            String contentType = null;
            contentType = adjunct.getContentType();
            if (contentType != null) {
                // /logger.debug("设置内容类型:" + contentType);
                response.setContentType(contentType);// set the MIME type.
            } else {
                response.setContentType("multipart/form-data");// set the
                // MIME
                // type.
            }
            // /////////////////////////设置文件下载名称Content-Disposition///////////////////////////
//            if("bytes=0-1".equals(range)){
//                response.reset();
//
//                response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED);
//            }
            response.setHeader("Content-Length", String.valueOf(contentLength));
            os = response.getOutputStream();
            out = new BufferedOutputStream(os);
            raf = new RandomAccessFile(downloadFile, "r");
            try {
                long outLength = 0;// 实际输出字节数
                switch (rangeSwitch) {
                    case 0: {// 普通下载，或者从头开始的下载
                        // 同1，没有break
                    }
                    case 1: {// 针对 bytes=27000- 的请求
                        raf.seek(pastLength);// 形如 bytes=969998336- 的客户端请求，跳过
                        // 969998336 个字节
                        int n = 0;
                        while ((n = raf.read(b)) != -1) {
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        // while ((n = raf.read(b, 0, 1024)) != -1) {
                        // out.write(b, 0, n);
                        // }
                        break;
                    }
                    case 2: {
                        // 针对 bytes=27000-39000 的请求，从27000开始写数据
                        raf.seek(pastLength);
                        int n = 0;
                        long readLength = 0;// 记录已读字节数
                        while (readLength <= contentLength - bsize) {// 大部分字节在这里读取
                            n = raf.read(b);
                            readLength += n;
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        if (readLength <= contentLength) {// 余下的不足 1024 个字节在这里读取
                            n = raf.read(b, 0, (int) (contentLength - readLength));
                            out.write(b, 0, n);
                            outLength += n;
                        }
                        break;
                    }
                    default: {
                        break;
                    }
                }
                System.out.println("Content-Length为：" + contentLength + "；实际输出字节数：" + outLength);
                out.flush();
            } catch (IOException ie) {
                /**
                 * 在写数据的时候， 对于 ClientAbortException 之类的异常，
                 * 是因为客户端取消了下载，而服务器端继续向浏览器写入数据时， 抛出这个异常，这个是正常的。
                 * 尤其是对于迅雷这种吸血的客户端软件， 明明已经有一个线程在读取 bytes=1275856879-1275877358，
                 * 如果短时间内没有读取完毕，迅雷会再启第二个、第三个。。。线程来读取相同的字节段， 直到有一个线程读取完毕，迅雷会 KILL
                 * 掉其他正在下载同一字节段的线程， 强行中止字节读出，造成服务器抛 ClientAbortException。
                 * 所以，我们忽略这种异常
                 */
                // ignore
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    if(e instanceof ClientAbortException){
                        logger.info("#提醒# 向客户端传输时出现IO异常，但此异常是允许的的，有可能客户端取消了下载，导致此异常，不用关心！");
                    }else {
                        e.printStackTrace();
                    }
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return res;
    }

    @Override
    public BaseResponse fileBatchDownload(HttpServletRequest request, HttpServletResponse response, String adjunctIds) throws IOException {
        BaseResponse res = new BaseResponse(StatusCode.SUCCESS);
        String[] adjunctIdArray = adjunctIds.split(",");
        //如果只有一份文件，则调用不同下载接口
        if(adjunctIdArray.length == 1){
            fileDownload(response,adjunctIdArray[0],null);
            return res;
        }
        //生成压缩包名称
        String finalFileName = UUID.randomUUID().toString().replace("-","")+".zip";
        int len;
        byte[] buffer = new byte[1024];
        File zipFile = new File(uploadPath+"/"+finalFileName);
        //压缩文件输出流
        ZipOutputStream zout=new ZipOutputStream(new FileOutputStream(zipFile));

        //遍历文件id集合
        for (String adjunctId:adjunctIdArray) {
            Adjunct adjunct = adjunctMapper.getById(adjunctId);
            if(adjunct == null){
                res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
                return res;
            }
            String path = adjunct.getPath();
            String realFileName = adjunct.getTitle()+"."+adjunct.getPrefix();
            File file = new File(path);
            if(!file.exists()){
                res = new BaseResponse(StatusCode.FILE_NOT_FOUND);
                return res;
            }
            //将需要压缩的文件格式化为输入流
            FileInputStream in = new FileInputStream(file);
            //压缩条目不是具体独立的文件，而是压缩包文件列表中的列表项，称为条目，就像索引一样
            ZipEntry zipEntry = new ZipEntry(realFileName);
            //定位该压缩条目位置，开始写入文件到压缩包中
            zout.putNextEntry(zipEntry);
            while ((len = in.read(buffer)) > 0) {
                zout.write(buffer, 0, len);
            }
            zout.closeEntry();
            in.close();
        }
        zout.close();
        // 1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        // 2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(finalFileName.getBytes("utf-8"), "ISO8859-1"));
        ServletOutputStream out;
        // 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
        FileInputStream inputStream = new FileInputStream(zipFile);
        // 3.通过response获取ServletOutputStream对象(out)
        out = response.getOutputStream();
        while ((len=inputStream.read(buffer)) != -1) {
            // 4.写到输出流(out)中
            out.write(buffer, 0, len);
        }
        inputStream.close();
        out.close();
        out.flush();
        //删除压缩包
        zipFile.delete();
        return res;
    }

}
